package yartiss.engine.simulation.io;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import yartiss.engine.simulation.system.ITask;
import yartiss.engine.simulation.system.schedulable.SchedulableFactory;

public class TasksetReader {

	private final Scanner scanner;
	private String[] lastline = null;

	/**
	 * 
	 * @param source
	 * @throws FileNotFoundException
	 */
	public TasksetReader(String source) throws FileNotFoundException {
		this(new File(source));
	}

	/**
	 * 
	 * @param source
	 */
	public TasksetReader(InputStream source) {
		scanner = new Scanner(source);
	}

	/**
	 * 
	 * @param source
	 * @throws FileNotFoundException
	 */
	public TasksetReader(File source) throws FileNotFoundException {
		scanner = new Scanner(source);
	}

	/**
	 * Reads taskset information out of a file, and creates the corresponding
	 * tasksets according to their types (simple, graph, ...)
	 * 
	 * @return the created array of tasks
	 */
	public ITask[] readTaskSet() {
		List<ITask> tasks = new ArrayList<ITask>();
		while (scanner.hasNext()) {
			String line = scanner.nextLine();
			lastline = line.split(" ");
			if (lastline.length == 3) {
				if (!tasks.isEmpty()) {
					ITask[] tab = new ITask[tasks.size()];
					return tasks.toArray(tab);
				}
				tasks.clear();
			} else if (lastline.length > 3) {
				long start = 0, wcet = 0, wcee = 0, period = 0, deadline = 0;
				int priority = 0;
				String type = "simple";

				for (int i = 0; i < lastline.length; i++) {
					String param = lastline[i].toLowerCase();
					if("type".equals(param)) {
						type = lastline[i + 2];
					}
					else if("period".equals(param)) {
						period = Long.parseLong(lastline[i + 2]);
					}
					else if("cost".equals(param) || "wcet".equals(param)) {
						wcet = Long.parseLong(lastline[i + 2]);
					}
					else if("deadline".equals(param)) {
						deadline = Long.parseLong(lastline[i + 2]);
					}
					else if("firstrelease".equals(param) || "start".equals(param)) {
						start = Long.parseLong(lastline[i + 2]);
					}
					else if("wcee".equals(param)) {
						wcee = Long.parseLong(lastline[i + 2]);
					}
					else if("priorirty".equals(param)) {
						priority = Integer.parseInt(lastline[i + 2]);
					}


				}
				tasks.add(SchedulableFactory.newInstance(type, start, wcet,	wcee, period, deadline, priority));
			}
		}
		if (!tasks.isEmpty()) {
			ITask[] tab = new ITask[tasks.size()];
			return tasks.toArray(tab);
		}
		return null;
	}

	/**
	 * 
	 * @return
	 */
	public List<ITask[]> readAllTaskSets() {
		List<ITask[]> sets = new ArrayList<ITask[]>();
		ITask[] set = null;
		while ((set = readTaskSet()) != null) {
			sets.add(set);
		}
		return sets;
	}

	/**
	 * 
	 */
	public void close() {
		scanner.close();
	}
}
